#!/usr/bin/env python3
"""
环境检查工具 - 检查所有依赖和相机状态
"""

import sys
import subprocess

def check_python_version():
    """检查Python版本"""
    print("="*60)
    print("🐍 检查Python版本")
    print("="*60)
    version = sys.version_info
    print(f"Python版本: {version.major}.{version.minor}.{version.micro}")
    
    if version.major < 3 or (version.major == 3 and version.minor < 8):
        print("❌ Python版本过低，需要3.8或更高版本")
        return False
    else:
        print("✅ Python版本符合要求")
        return True

def check_python_packages():
    """检查Python包"""
    print("\n" + "="*60)
    print("📦 检查Python包依赖")
    print("="*60)
    
    required_packages = {
        'numpy': 'NumPy',
        'cv2': 'OpenCV',
        'open3d': 'Open3D',
        'PIL': 'Pillow',
    }
    
    optional_packages = {
        'primesense': 'OpenNI2 (Orbbec相机)',
        'pyrealsense2': 'RealSense SDK',
    }
    
    all_ok = True
    
    print("\n必需包:")
    for module_name, display_name in required_packages.items():
        try:
            __import__(module_name)
            print(f"  ✅ {display_name}")
        except ImportError:
            print(f"  ❌ {display_name} - 未安装")
            all_ok = False
    
    print("\n可选包:")
    for module_name, display_name in optional_packages.items():
        try:
            __import__(module_name)
            print(f"  ✅ {display_name}")
        except ImportError:
            print(f"  ⚠️  {display_name} - 未安装（如需使用对应相机请安装）")
    
    return all_ok

def check_camera():
    """检查相机连接"""
    print("\n" + "="*60)
    print("📷 检查相机连接")
    print("="*60)
    
    # 检查OpenNI2相机
    try:
        from primesense import openni2
        try:
            openni2.initialize()
            dev = openni2.Device.open_any()
            info = dev.get_device_info()
            name = info.name.decode() if isinstance(info.name, bytes) else str(info.name)
            print(f"  ✅ OpenNI2相机已连接: {name}")
            openni2.unload()
            return True
        except Exception as e:
            print(f"  ⚠️  OpenNI2相机未连接或驱动未安装")
            openni2.unload()
    except ImportError:
        print(f"  ⚠️  OpenNI2 Python包未安装")
    
    # 检查UVC相机
    try:
        import cv2
        cap = cv2.VideoCapture(0)
        if cap.isOpened():
            ret, _ = cap.read()
            if ret:
                print(f"  ✅ UVC相机已连接")
                cap.release()
                return True
        cap.release()
    except Exception:
        pass
    
    print(f"  ❌ 未检测到相机")
    return False

def check_openni2_driver():
    """检查OpenNI2驱动"""
    print("\n" + "="*60)
    print("🔧 检查OpenNI2驱动")
    print("="*60)
    
    import os
    from pathlib import Path
    
    # 常见安装路径
    paths = [
        r"C:\Program Files\OpenNI2\Redist",
        r"C:\Program Files (x86)\OpenNI2\Redist",
        r"C:\Program Files\Orbbec\OpenNI2\Redist",
        r"C:\Program Files (x86)\Orbbec\OpenNI2\Redist",
    ]
    
    found = False
    for path in paths:
        if Path(path).exists():
            print(f"  ✅ 找到OpenNI2驱动: {path}")
            found = True
            break
    
    if not found:
        print(f"  ⚠️  未找到OpenNI2驱动")
        print(f"\n  请下载并安装 Orbbec OpenNI2 SDK:")
        print(f"  https://orbbec3d.com/index/download.html")
    
    return found

def main():
    """主函数"""
    print("\n")
    print("╔" + "="*58 + "╗")
    print("║" + " "*15 + "环境检查工具" + " "*31 + "║")
    print("║" + " "*10 + "www.gdrsgg.com   309647724@qq.com" + " "*14 + "║")
    print("╚" + "="*58 + "╝")
    print("\n")
    
    results = []
    
    # 执行检查
    results.append(("Python版本", check_python_version()))
    results.append(("Python包", check_python_packages()))
    results.append(("OpenNI2驱动", check_openni2_driver()))
    results.append(("相机连接", check_camera()))
    
    # 总结
    print("\n" + "="*60)
    print("📊 检查结果总结")
    print("="*60)
    
    for name, status in results:
        status_icon = "✅" if status else "❌"
        print(f"  {status_icon} {name}")
    
    all_pass = all(status for _, status in results[:2])  # 只要求Python和包
    
    print("\n" + "="*60)
    if all_pass:
        print("✅ 环境检查通过！可以开始使用")
        print("\n运行以下命令启动程序:")
        print("  python tools/gui_launcher.py")
    else:
        print("❌ 环境检查未通过，请先安装缺少的依赖")
        print("\n安装依赖:")
        print("  pip install -r requirements-rgbd.txt")
    print("="*60)
    print("\n")
    
    return 0 if all_pass else 1

if __name__ == "__main__":
    try:
        exit_code = main()
        input("\n按回车键退出...")
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n\n用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ 错误: {e}")
        import traceback
        traceback.print_exc()
        input("\n按回车键退出...")
        sys.exit(1)

